import User from '@/store/user'
import * as toast from '@/util/toast/toast'
import * as hexUtil from './hexUtil'
import * as api from '@/api/index'
import * as btUtil from './btUtil'
import moment from 'moment'
export function handleDeviceWarningUpload(warnBlock:any){//处理警告提示及弹窗
    let  commend = User.currentChoosedMachineBleData.warn_status_tips;

    // commend = "1e5c";
    // commend = "512";

    if(commend === null || commend === undefined || commend === ''){
        return
    }
    
            //十进制数据
        let dec_warn_status =  commend
            //二进制数据
        let binary_warn_status = hexUtil.decimalStringToBinary(dec_warn_status);
            
        while (binary_warn_status.length < 12) {
            binary_warn_status = "0"+binary_warn_status;
        }
        if(binary_warn_status === '000000000000'){
            User.currentConnectedEquipment.warning_tips = ''
        }


        // console.log('报警状态12位：'+binary_warn_status)
    
        //电池电量低报警
        let battery_electricity_lower_warn = "";
        //控制器报警
    //    let control_warn = "";
        //温度高报警
        let temperature_higher_warn = "";
        //机油少报警
        let oil_lower_warn = "";
        //汽油少报警
        let gas_lower_warn = "";
        
        
        let tmp_electricty_lower_warn_0 = "";
        let tmp_electricty_lower_warn_1 = "";
        let tmp_electricty_lower_warn_2 = "";
        let tmp_electricty_lower_warn_3 = "";
        let tmp_electricty_lower_warn_4 = "";


     
        
        
        if(binary_warn_status.length > 0){
            tmp_electricty_lower_warn_0 =  binary_warn_status.slice(binary_warn_status.length-1,binary_warn_status.length);
        }
        if(binary_warn_status.length > 1){
            tmp_electricty_lower_warn_1 = binary_warn_status.slice(binary_warn_status.length-2,binary_warn_status.length-1);
        }
        if(binary_warn_status.length > 2){
            tmp_electricty_lower_warn_2 = binary_warn_status.slice(binary_warn_status.length-3,binary_warn_status.length-2);
        }
        if(binary_warn_status.length > 3){
            tmp_electricty_lower_warn_3 = binary_warn_status.slice(binary_warn_status.length-4,binary_warn_status.length-3);
        }
        if(binary_warn_status.length > 4){
            tmp_electricty_lower_warn_4 = binary_warn_status.slice(binary_warn_status.length-5,binary_warn_status.length-4);
        }
        
        
       
        if(binary_warn_status.length > 9){
            gas_lower_warn =  binary_warn_status.slice(binary_warn_status.length-9,binary_warn_status.length-8); 
        }
        if(binary_warn_status.length > 10){
            oil_lower_warn =  binary_warn_status.slice(binary_warn_status.length-10,binary_warn_status.length-9); 
        }
        if(binary_warn_status.length >11){
            temperature_higher_warn =  binary_warn_status.slice(binary_warn_status.length-11,binary_warn_status.length-10); 
        }
        
        if(parseInt(tmp_electricty_lower_warn_0) === 1 ||
            parseInt(tmp_electricty_lower_warn_1) == 1 ||
            parseInt(tmp_electricty_lower_warn_2) == 1 ||
            parseInt(tmp_electricty_lower_warn_3) == 1 ||
            parseInt(tmp_electricty_lower_warn_4) == 1 ){
            battery_electricity_lower_warn = "1";
        }else{
             battery_electricity_lower_warn = "";
        }

        // temperature_higher_warn = Math.floor(Math.random()*2) + ''
        // oil_lower_warn = Math.floor(Math.random()*2) + ''
        // gas_lower_warn = Math.floor(Math.random()*2) + ''
        // tmp_electricty_lower_warn_0 = Math.floor(Math.random()*2) + ''
        // tmp_electricty_lower_warn_1 = Math.floor(Math.random()*2) + ''
        // tmp_electricty_lower_warn_2 = Math.floor(Math.random()*2) + ''
        // tmp_electricty_lower_warn_3 = Math.floor(Math.random()*2) + ''
        // tmp_electricty_lower_warn_4 = Math.floor(Math.random()*2) + ''
        // oil_lower_warn = '0'

        // console.log('tmp_electricty_lower_warn_0:'+tmp_electricty_lower_warn_0)
        // console.log('tmp_electricty_lower_warn_1:'+tmp_electricty_lower_warn_1)
        // console.log('tmp_electricty_lower_warn_2:'+tmp_electricty_lower_warn_2)
        // console.log('tmp_electricty_lower_warn_3:'+tmp_electricty_lower_warn_3)
        // console.log('tmp_electricty_lower_warn_4:'+tmp_electricty_lower_warn_4)
        // console.log('temperature_higher_warn:'+temperature_higher_warn)
        // console.log('oil_lower_warn:'+oil_lower_warn)
        // console.log('gas_lower_warn:'+gas_lower_warn)
    
     

        
        //判断报警提示文案
        let warnAlertMsgList = [] as any;
        if(parseInt(tmp_electricty_lower_warn_0) == 1){
            warnAlertMsgList.push("低压报警")
            uploadWarningDataWithFaultType("低压报警");
        }
        if(parseInt(tmp_electricty_lower_warn_1) == 1){
            warnAlertMsgList.push("高压报警");
            uploadWarningDataWithFaultType("高压报警");
        }
        if(parseInt(tmp_electricty_lower_warn_2) == 1){
            warnAlertMsgList.push("启动报警");
            uploadWarningDataWithFaultType("启动报警");
        }
        if(parseInt(tmp_electricty_lower_warn_3) == 1){
            warnAlertMsgList.push("控制器报警");
            uploadWarningDataWithFaultType("控制器报警");
        }
        if(parseInt(tmp_electricty_lower_warn_4) == 1){
            warnAlertMsgList.push("电路报警");
            uploadWarningDataWithFaultType("电路报警");
        }
        if(parseInt(temperature_higher_warn) == 1){
            warnAlertMsgList.push("温度高报警");
            uploadWarningDataWithFaultType("温度高报警");
        }
        if(parseInt(oil_lower_warn) == 1){
            warnAlertMsgList.push("机油保养报警");
            console.log('是否可以发送保养提示:'+User.currentConnectedEquipment.canSendMaintainTips)
            if(User.currentConnectedEquipment.canSendMaintainTips)
            {
                uploadMaintinTips();
            }
        }
        if(parseInt(gas_lower_warn) == 1){
            warnAlertMsgList.push("汽油少报警");
            uploadWarningDataWithFaultType("汽油少报警");
        }
        if(warnAlertMsgList.length > 0){
            
    
            let msg = warnAlertMsgList.join(',');
            if(User.currentConnectedEquipment.warning_tips !== msg){     
                // uni.showModal({
                //     title: '报警信息',
                //     content:msg,
                //     confirmText:'我知道了',
                //     showCancel:false,
                //     success: function (res) {
                //     }
                // });
                if(msg.includes('机油保养报警')){
                    warnBlock('机油保养报警')
                }else{
                    warnBlock(msg)
                }
                
                User.currentConnectedEquipment.warning_tips = msg
            }

        }
            
        
        
        User.currentConnectedEquipment.battery_electricity_lower_warn = battery_electricity_lower_warn;
        User.currentConnectedEquipment.temperature_higher_warn = temperature_higher_warn;
    //    User.currentConnectedEquipment.control_warn = control_warn;
        User.currentConnectedEquipment.oil_lower_warn = oil_lower_warn;
        User.currentConnectedEquipment.gas_lower_warn = gas_lower_warn;
        
}
export function uploadMaintinTips(){//上传维修提示
    // console.log('开始上传保养信息')
    // btUtil.sendCMD('BLE_COMMEND_CLEAR_OIL_WARNING',function(res:any){
    // });
    // return;


    if(User.currentConnectedEquipment === null || User.currentConnectedEquipment === undefined || User.currentConnectedEquipment.deviceID === ''){
        return
    }

   let param = {
        "deviceid":User.currentConnectedEquipment.deviceID,
        "totaltime":User.currentConnectedEquipment.single_run_time !==null && User.currentConnectedEquipment.single_run_time !== undefined ? User.currentConnectedEquipment.single_run_time : '' ,
        "totalruntime":User.currentConnectedEquipment.total_run_time !==null && User.currentConnectedEquipment.total_run_time !== undefined ? User.currentConnectedEquipment.total_run_time : '' ,
        "totalpower":User.currentConnectedEquipment.total_power_power !==null && User.currentConnectedEquipment.total_power_power !== undefined ? User.currentConnectedEquipment.total_power_power : '' ,
    };
    console.log('上传保养信息入参：'+JSON.stringify(param))

    api.sendMaintainTipRequest(param).then(function(res){
        console.log('上传保养信息返参：'+JSON.stringify(res))

        // addMaintainRecord()

    });
}

export function addMaintainRecord(){

  let date =   moment(new Date()).format('yyyy-MM-dd HH:mm')
   let model = {
        bydate:date,
        bytypename:'机油保养',
        bytype:1,
        byaddress:'',
        bycontent:'机油少报警',
        attachgids:'',
        deviceid:User.currentConnectedEquipment.deviceID

    } as any;
    api.addDeviceReq(model).then(function(res:any){

        if(res.success){
            btUtil.sendCMD('BLE_COMMEND_CLEAR_OIL_WARNING',function(res:any){
            });
        }
    });
        
}


export function uploadWarningDataWithFaultType(type:string){//上传警告信息
    // console.log('开始上传警告信息')
    if(User.currentConnectedEquipment === null || User.currentConnectedEquipment === undefined || User.currentConnectedEquipment ===  ''){
        return
    }
    let param = {"deviceid":User.currentConnectedEquipment.deviceID,
        "fc":type,
        "vo":User.currentConnectedEquipment.curr_voltage !==null && User.currentConnectedEquipment.curr_voltage !== undefined ? User.currentConnectedEquipment.curr_voltage : '' ,   //电压
        "po":User.currentConnectedEquipment.curr_power !==null && User.currentConnectedEquipment.curr_power !== undefined ? User.currentConnectedEquipment.curr_power : '' ,   //功率
        "sp":User.currentConnectedEquipment.curr_speed !==null && User.currentConnectedEquipment.curr_speed !== undefined ? User.currentConnectedEquipment.curr_speed : '' ,    //转速
        "gas":User.currentConnectedEquipment.curr_gas !==null && User.currentConnectedEquipment.curr_gas !== undefined ? User.currentConnectedEquipment.curr_gas : '' , //油门
        "temp":User.currentConnectedEquipment.curr_temperature !==null && User.currentConnectedEquipment.curr_temperature !== undefined ? User.currentConnectedEquipment.curr_temperature : '' ,
    };
    // console.log('上传警告信息入参：'+JSON.stringify(param))

    api.addFaultRecordReq(param).then(function(res){
        // console.log('上传警告信息返参：'+JSON.stringify(res))

    });

}

///上报设备的实时数据
export function uploadDeviceDataReq(){

    if(User.currentConnectedEquipment === null || User.currentConnectedEquipment === undefined || User.currentConnectedEquipment ===  ''){
        return
    }

    uploadVoltageData()
    uploadPowerData()
    uploadSpeedData()
    uploadGasData()
    uploadRuntimeData()
    uploadBlueToothStatusData()
}


///上报电压信息
export function uploadVoltageData(){

    if(User.voltageList === null || User.voltageList.length < 1){
        return
    }
    if(User.currentConnectedEquipment.deviceID === null || User.currentConnectedEquipment.deviceID === undefined || User.currentConnectedEquipment.deviceID === ''){
        return
    }

    let array = [] as any
    User.voltageList.forEach((element:any) => {
        let param = {'did':User.currentConnectedEquipment.deviceID,
                     'vo':element.data,
                     'ud':element.timestamp
        }
        array.push(param)
    });
    let param = {'voltageinfo':JSON.stringify(array)};
    api.reportVoltageinfoReq(param).then((res:any)=>{

    })

}

///上报功率信息
export function uploadPowerData(){

    if(User.powerList === null || User.powerList.length < 1){
        return
    }
    if(User.currentConnectedEquipment.deviceID === null || User.currentConnectedEquipment.deviceID === undefined || User.currentConnectedEquipment.deviceID === ''){
        return
    }

    let array = [] as any
    User.powerList.forEach((element:any) => {
        let param = {'did':User.currentConnectedEquipment.deviceID,
                     'po':element.data,
                     'ud':element.timestamp
        }
        array.push(param)
    });
    let param = {'powerinfo':JSON.stringify(array)};
    api.reportPowerinfoReq(param).then((res:any)=>{
        User.powerList = [] as any
    })

}


///上报转速信息
export function uploadSpeedData(){

    if(User.speedList === null || User.speedList.length < 1){
        return
    }
    if(User.currentConnectedEquipment.deviceID === null || User.currentConnectedEquipment.deviceID === undefined || User.currentConnectedEquipment.deviceID === ''){
        return
    }

    let array = [] as any
    User.speedList.forEach((element:any) => {
        let param = {'did':User.currentConnectedEquipment.deviceID,
                     'sp':element.data,
                     'ud':element.timestamp
        }
        array.push(param)
    });
    let param = {'speedinfo':JSON.stringify(array)};
    api.reportSpeedinfoReq(param).then((res:any)=>{
        User.speedList = [] as any

    })

}

///上报转速信息
export function uploadGasData(){

    if(User.acceleratorList === null || User.acceleratorList.length < 1){
        return
    }
    if(User.currentConnectedEquipment.deviceID === null || User.currentConnectedEquipment.deviceID === undefined || User.currentConnectedEquipment.deviceID === ''){
        return
    }

    let array = [] as any
    User.acceleratorList.forEach((element:any) => {
        let param = {'did':User.currentConnectedEquipment.deviceID,
                     'gas':element.data,
                     'ud':element.timestamp
        }
        array.push(param)
    });
    let param = {'gasinfo':JSON.stringify(array)};
    api.reportGasinfoReq(param).then((res:any)=>{
        User.acceleratorList = [] as any

    })

}

///上报运行时间信息
export function uploadRuntimeData(){

    if(User.runtimeList === null || User.runtimeList.length < 1){
        return
    }
    if(User.currentConnectedEquipment.deviceID === null || User.currentConnectedEquipment.deviceID === undefined || User.currentConnectedEquipment.deviceID === ''){
        return
    }

    let array = [] as any
    User.runtimeList.forEach((element:any) => {
        let param = {'did':User.currentConnectedEquipment.deviceID,
                     'st':element.singleUseTime,
                     'sp':element.singleElc,
                     'ct':element.totalUseTime,
                     'cp':element.totalElc,
                     'ud':element.timestamp
        }
        array.push(param)
    });
    let param = {'cumulativeinfo':JSON.stringify(array)};
    api.reportRuntimeReq(param).then((res:any)=>{
        User.runtimeList = [] as any

    })

}

///上报蓝牙连接状态
export function uploadBlueToothStatusData(){

    if(User.currentConnectedEquipment.deviceID === '' || User.currentConnectedEquipment.deviceID === null || User.currentConnectedEquipment.deviceID ===undefined){
        return
    }

    let param = {'deviceid':User.currentConnectedEquipment.deviceID,
                    'status':User.isConnectedBlueTooth ? '1' : '0',
    }
    // console.log('蓝牙状态上传参数：'+JSON.stringify(param))
    api.reportBlueToothinfo(param).then((res:any)=>{

        // console.log('蓝牙状态上传结果：'+JSON.stringify(res))


    })

}

